<?php

/**
 * Class YMobileValidator
 */
class YMobileValidator extends CValidator
{
	public $skipOnError = true;

	public $pattern = '/^1[3|4|5|8][0-9]\d{4,8}$/';

	public $allowEmpty = true;

	public function validateAttribute($object, $attribute)
	{
		$value = $object->$attribute;
		if ($this->allowEmpty && $this->isEmpty($value)) {
			return;
		}

		if (!preg_match($this->pattern, $value)) {
			$this->addError($object, $attribute, $this->message ? $this->message : '{attribute} 格式不正确.');
		}
	}

	public function clientValidateAttribute($object, $attribute)
	{
		$message = $this->message;

		if ($message === null) {
			$message = '{attribute} 格式不正确.';
		}

		$message = strtr($message, array(
			'{attribute}' => $object->getAttributeLabel($attribute),
		));

		$condition = "!{$this->pattern}.test(value)";
		return "
if(" . ($this->allowEmpty ? "jQuery.trim(value)!='' && " : '') . $condition . ") {
	messages.push(" . CJSON::encode($message) . ");
}
";
	}
}